using Dapper;
using MediatR;
using RBAC.Domain.RBAC;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using RBAC.Read.Api.Application.Dto.ERP;

namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 获取用户选项列表（仅 Id、Name）
    /// </summary>
    public class GetUserListHandler : IRequestHandler<GetUserListCommand, APIResult<List<UserOptionDto>>>
    {
        private readonly IBaseRepository<UserModel> _userRepo;

        public GetUserListHandler(IBaseRepository<UserModel> userRepo)
        {
            _userRepo = userRepo;
        }

        public Task<APIResult<List<UserOptionDto>>> Handle(GetUserListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var kw = request.Keyword?.Trim();
                var top = request.Top <= 0 ? 20 : request.Top;
                if (top > 50) top = 50; // 限制最大返回数量

                var sql = @"SELECT Id, UserName AS Name FROM User WHERE IsDeleted = FALSE";
                var param = new DynamicParameters();
                if (!string.IsNullOrWhiteSpace(kw))
                {
                    sql += " AND UserName LIKE @kw";
                    param.Add("@kw", $"%{kw}%");
                }
                sql += " ORDER BY Id DESC LIMIT @Top";
                param.Add("@Top", top);

                var list = _userRepo.Query<UserOptionDto>(sql, param);

                return Task.FromResult(new APIResult<List<UserOptionDto>>
                {
                    Code = APIEnums.Success,
                    Msg = "获取成功",
                    Data = list
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<List<UserOptionDto>>
                {
                    Code = APIEnums.Fail,
                    Msg = "获取失败：" + ex.Message,
                    Data = new List<UserOptionDto>()
                });
            }
        }
    }
}
